package models

import (
	"errors"
	"fmt"
	"reflect"
	"strconv"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

const JwtString = "!#FDSASDFASDF@#343423"

type Classmates struct {
	Id        int    `orm:"column(id);auto"`
	Name      string `orm:"column(name);size(50);null" description:"姓名"`
	Sn        string `orm:"column(sn);size(255);null" description:"学号"`
	Sex       string `orm:"column(sex);size(5);null" description:"性别"`
	Tel       string `orm:"column(tel);size(15);null" description:"电话"`
	Email     string `orm:"column(email);size(15);null" description:"email"`
	Grade     int    `orm:"column(grade);null" description:"年级"`
	Classname string `orm:"column(classname);size(55);null" description:"邮箱"`
	Comments  string `orm:"column(comments);size(255);null" description:"备注"`
	Xueji     string `orm:"column(xueji);size(55);null" description:"学籍"`
	Status    string `orm:"column(status);size(55);null" description:"状态"`
	IP1       string `orm:"column(ip1);size(55);null" description:"IP1"`
	IP2       string `orm:"column(ip2);size(55);null" description:"IP2"`
	IP3       string `orm:"column(ip3);size(55);null" description:"IP3"`
	PSWD      string `orm:"column(pswd);size(55);null" description:"密码"`
	Gitee     string `orm:"column(gitee);size(155);null" description:"Gitee"`
}

func (t *Classmates) TableName() string {
	return "classmates"
}

func init() {
	orm.RegisterModel(new(Classmates))
}

// AddClassmates insert a new Classmates into database and returns
// last inserted Id on success.
func AddClassmates(m *Classmates) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetClassmatesById retrieves Classmates by Id. Returns error if
// Id doesn't exist
func GetClassmatesById(id int) (v *Classmates, err error) {
	o := orm.NewOrm()
	v = &Classmates{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

var AllClassMates map[string]*Classmates

func LoadAllClassMates() {
	if AllClassMates == nil {
		AllClassMates = make(map[string]*Classmates)
	}
	go func() {
		for {
			classmates, err := GetAllClassmates(nil, nil, nil, nil, 0, 100000)
			if err != nil {
				time.Sleep(time.Minute)
				continue
			}
			for _, item := range classmates {
				classmate := item.(Classmates)
				classmate.Sn = strings.Trim(classmate.Sn, " ")
				classmate.Name = strings.Trim(classmate.Name, " ")
				AllClassMates[classmate.Sn] = &classmate
			}
			time.Sleep(time.Minute)
		}
	}()

}

// GetAllClassmates retrieves all Classmates matches certain condition. Returns empty list if
// no records exist
func GetAllClassmates(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Classmates))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Classmates
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

func UpdatePswdById(id int64, sn, newpswd string) (item *Classmates, err error) {
	o := orm.NewOrm()
	item = new(Classmates)
	sqlstr := "update " + item.TableName() + " set pswd='" + newpswd + "' where id=" + strconv.Itoa(int(id))

	rs := o.Raw(sqlstr)
	_, err = rs.Exec()
	if err != nil {
		return
	}
	item.Id = int(id)
	if err = o.Read(item); err == nil {
		return item, nil
	}

	return
}
func UpdateClassmatesById(m *Classmates) (err error) {
	o := orm.NewOrm()
	v := Classmates{Id: m.Id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}
